// 获取 matchId 和 playerId 从 URL 参数
const urlParams = new URLSearchParams(window.location.search);

const matchId = urlParams.get('matchId');
const playerId = urlParams.get('playerId');

// 当前页数
let currentPage = 1;
let totalPage = 0;

// 提交评分和评论
document.getElementById('submit-btn').addEventListener('click', async () => {

    const rating = document.getElementById('rating').value;
    const comment = document.getElementById('comment').value;

    // 校验用户输入
    if (!rating || rating < 0 || rating > 10) {
        alert("请输入到10之间的评分！");
        return;
    }
    if (!comment) {
        alert("评论不能为空！");
        return;
    }

    // 模拟提交评分和评论
    try {
        const token = sessionStorage.getItem("token");
        const response = await fetch('http://localhost:8081/comment/submit', {
            method: 'POST',
            headers: {
                'Authorization': token,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                matchId,
                playerId,
                rating,
                comment
            })
        });

        if (response.ok) {
            alert('评分和评论提交成功！');
            // 提交成功后清空输入框
            document.getElementById('rating').value = '';
            document.getElementById('comment').value = '';
            // 刷新评论列表
            fetchComments(currentPage);
        } else {
            const errorData = await response.json();
            alert(`提交失败: ${errorData.message}`);
        }
    } catch (error) {
        console.error('提交评分和评论时发生错误:', error);
        alert('提交失败，请稍后再试。');
    }
});

// 分页获取评论
async function fetchComments(page) {
    const token = sessionStorage.getItem("token");

    try {
        const response = await fetch(`http://localhost:8081/comment/comments?matchId=${matchId}&playerId=${playerId}&page=${page}`, {
            method: 'GET',
            headers: {
                'Authorization': token
            }
        });

        if (response.ok) {
            const data = await response.json();
            console.log(data);
            renderComments(data.comments);
            togglePaginationButtons(data.hasNext, data.hasPrevious);
            document.getElementById('current-page').innerText = page;
            totalPage = data.totalPageSize;
        } else {
            console.error('获取评论失败:', response.statusText);
        }
    } catch (error) {
        console.error('获取评论时发生错误:', error);
    }
}

// 渲染评论到页面
function renderComments(comments) {
    const commentList = document.getElementById('comment-list');
    commentList.innerHTML = ''; // 清空之前的评论
    const playerName = new URLSearchParams(window.location.search).get('playerName')
    comments.forEach(comment => {
        const commentHtml = `
            <div class="comment">
                <p> ------ ${playerName} 超话 --------
                <p>用户: ${comment.username}</p>
                <p>评分: ${comment.rating}</p>
                <p>评论: ${comment.msg}</p>
            </div>
        `;
        commentList.insertAdjacentHTML('beforeend', commentHtml);
    });
}

// 切换分页按钮的状态
function togglePaginationButtons() {  
    document.getElementById('prev-page').disabled = currentPage === 1;  
    document.getElementById('next-page').disabled = currentPage === totalPage;  
}  

// 监听分页按钮
document.getElementById('prev-page').addEventListener('click', () => {
    if (currentPage > 1) {
        currentPage--;
        fetchComments(currentPage);
    }
});
document.getElementById('next-page').addEventListener('click', () => {
    currentPage++;
    fetchComments(currentPage);
});

// 页面加载时获取第一页的评论
document.addEventListener('DOMContentLoaded', () => {
    fetchComments(currentPage);
});
